package lambdasinaction.chap11.CountDownLatch;

import java.util.concurrent.CountDownLatch;

/**
 * 将一个大任务分解为多个子任务，并在所有子任务完成后汇总结果。
 */
public class TaskDivision {

    public static void main(String[] args) throws InterruptedException {
        int numberOfSubTasks = 4;
        CountDownLatch latch = new CountDownLatch(numberOfSubTasks);

        for (int i = 0; i < numberOfSubTasks; i++) {
            new Thread(new SubTask(latch)).start();
        }

        // Main thread waits for all sub-tasks to complete
        latch.await();
        System.out.println("All sub-tasks are completed. Aggregating results...");
        // Aggregate results here
    }
}

class SubTask implements Runnable {
    private CountDownLatch latch;

    public SubTask(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {
        try {
            System.out.println("SubTask " + Thread.currentThread().getId() + " is processing...");
            Thread.sleep(1000); // Simulate sub-task processing
            System.out.println("SubTask " + Thread.currentThread().getId() + " is done.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            latch.countDown(); // Decrement the count of the latch
        }
    }
}
